package com.hpf.community.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hpf.community.model.LogModel;
import com.hpf.community.service.ILogService;
import com.hpf.community.utils.PaginationResult;
import com.hpf.community.utils.StandardResult;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;


/**
 *
 * Log 控制器    日志表
 *
 * @author huangpengfei
 * @since 2020-04-04
 */

@RestController
public class LogController {
    private final Logger logger = LoggerFactory.getLogger(LogController.class);

    @Autowired
    public ILogService logService;

    /**
     * 获取分页列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/log")
    @RequiresRoles("3")
    public StandardResult selectPage(@ModelAttribute LogModel logModel, Integer pageSize,
                                     Integer pageNumber, String searchKey,
                                     Date startTime, Date endTime) {
        try {
            if (pageSize == null || pageNumber == null) {
                return StandardResult.faildCheck("缺少必要的分页参数！");
            }
            Page<LogModel> page = new Page<LogModel>(pageNumber, pageSize);
            Wrapper<LogModel> wrapper = new EntityWrapper<LogModel>();
            if (StringUtils.isNotBlank(searchKey)) {
                wrapper.like(LogModel.DESCRIPTION, searchKey);
                wrapper.or();
                wrapper.like(LogModel.CREATE_USERNAME, searchKey);
            }
            if (null != endTime) {
                wrapper.andNew();
                wrapper.le(LogModel.CREATE_DATETIME, endTime);
            }
            if (null != startTime) {
                wrapper.andNew();
                wrapper.ge(LogModel.CREATE_DATETIME, startTime);
            }
            wrapper.orderBy(LogModel.CREATE_DATETIME, false);
            logService.selectPage(page, wrapper);
            return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return PaginationResult.faild(e);
        }
    }

    /**
     * 获取列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/logList")
    public StandardResult selectList(@ModelAttribute LogModel logModel) {
        try {
            Wrapper<LogModel> wrapper = new EntityWrapper<LogModel>(logModel);
            return StandardResult.ok(null, logService.selectList(wrapper));
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 添加
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PostMapping("/log")
    public StandardResult insert(@ModelAttribute LogModel logModel) {
        try {
            logService.insert(logModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 修改
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PutMapping("/log")
    public StandardResult updateById(@RequestBody LogModel logModel) {
        try {
            logService.updateById(logModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 通过id获取详情
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/log/{id}")
    public StandardResult selectById(@PathVariable String id) {
        try {
            return StandardResult.ok(logService.selectById(id));
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 通过id删除数据
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @DeleteMapping("/log/{id}")
    public StandardResult deleteById(@PathVariable String id) {
        try {
            logService.deleteById(id);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response, @ModelAttribute LogModel logModel) {
        try {
            Wrapper<LogModel> wrapper = new EntityWrapper<>();
            List<LogModel> logModelList = logService.selectList(wrapper);
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("获取excel测试表格");
            HSSFRow row = null;
            row = sheet.createRow(0);//创建第一个单元格
            row.setHeight((short) (26.25 * 20));
            row.createCell(0).setCellValue("日志表");//为第一行单元格设值
            /*为标题设计空间
             * firstRow从第1行开始
             * lastRow从第0行结束
             *从第1个单元格开始
             * 从第3个单元格结束
             */
            CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
            sheet.addMergedRegion(rowRegion);
            /*CellRangeAddress columnRegion = new CellRangeAddress(1,4,0,0);
             sheet.addMergedRegion(columnRegion);*/
            /*
             * 动态获取数据库列 sql语句 select COLUMN_NAME from INFORMATION_SCHEMA.Columns where table_name='user' and table_schema='test'
             * 第一个table_name 表名字
             * 第二个table_name 数据库名称
             * */
            row = sheet.createRow(1);
            row.setHeight((short) (22.50 * 20));//设置行高
            row.createCell(0).setCellValue("日志描述");//为第一个单元格设值
            row.createCell(1).setCellValue("日志创建人");//为第二个单元格设值
            row.createCell(2).setCellValue("日志创建时间");//为第三个单元格设值

            for (int i = 0; i < logModelList.size(); i++) {
                row = sheet.createRow(i + 2);
                LogModel log = logModelList.get(i);
                row.createCell(0).setCellValue(log.getDescription());
                row.createCell(1).setCellValue(log.getCreateUsername());
                row.createCell(2).setCellValue(log.getCreateDatetime());
            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));
            //列宽自适应
            for (int i = 0; i <= 13; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            OutputStream os = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment;filename=user.xls");//默认Excel名称
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error("异常信息:", e);
        }
    }
}
